import { ActionContext } from 'vuex'
import db from '@/components/db'
import { Product } from '@/models/Product';
import _ from 'lodash';

interface State {
    products: Product[]
}
const initState = {
    products: []
}

const getters = {
    products(state: State) {
        return state.products
    }
}

const actions = {
    initProducts(context: ActionContext<State, any>) {
        return new Promise((resolve, reject) => {
            db.filter('product').then((products) => {
                let arr: Product[] = [];
                if (products instanceof Array) {
                    if (products.length > 0) {
                        products.forEach((item) => {
                            const p = new Product(item);
                            arr.push(p);
                        })
                    }
                }
                context.commit('initProducts', arr);
                resolve();
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    addProduct(context: ActionContext<State, any>, pro: Product) {
        return new Promise((resovle, reject) => {
            const product: Product = new Product(pro);
            db.insert('product', product).then((added) => {
                context.commit('addProduct', product);
                resovle(added)
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    updateProduct(context: ActionContext<State, any>, pro: Product) {
        return new Promise((resolve, reject) => {
            pro.update();
            db.update('product', pro).then(() => {
                context.commit('updateProduct', pro);
                resolve(pro);
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    deleteProduct(context: ActionContext<State, any>, pro: Product) {
        return new Promise((resolve, reject) => {
            db.delete('product', { id: pro.id }).then(result => {
                context.commit('deleteProduct', pro)
                resolve()
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    getProductById(context: ActionContext<State, any>, id: string) {
        return new Promise((resolve, reject) => {
            db.filter('product', { id }).then(result => {
                if (result instanceof Array) {
                    if (result.length > 0) {
                        let p = new Product(result[0]);
                        resolve(p)
                    } else {
                        reject(new Error('没有找到相关产品'))
                    }
                } else {
                    reject(new Error('数据库错误'))
                }
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    filterProduct(context: ActionContext<State, any>, filter: any) {
        return new Promise((resolve, reject) => {
            db.filter('product', filter).then((products) => {
                let result: Product[] = [];
                if (products instanceof Array) {
                    if (products.length > 0) {
                        console.log("找到的商品：", products)
                        products.forEach((item) => {
                            const p = new Product(item);
                            result.push(p);
                        })
                        resolve(result)
                    } else {
                        reject(new Error('没有找到相关产品'))
                    }
                } else {
                    reject(new Error('数据库错误'))
                }
            })
        })
    },
    reduceStock(context: ActionContext<State, any>, product: Product) {
        return new Promise((resolve, reject) => {
            product.reduceStock().catch(reason => {
                reject(reason);
                return;
            })
            context.dispatch('updateProduct', product).then(() => {
                resolve();
            }).catch(reason => {
                reject(reason);
            })
        })
    },
    increaseStock(context: ActionContext<State, any>, product: Product) {
        return new Promise((resolve, reject) => {
            context.dispatch('getProductById', product.id).then(result => {
                result.increaseStock();
                context.dispatch('updateProduct', result).then(() => {
                    resolve();
                }).catch(reason => {
                    reject(reason);
                })
            }).catch(reason => {
                reject(reason);
            })

        })
    }
}

const mutations = {
    initProducts(state: State, products: Product[]) {
        state.products = products;
        console.log("商品初始化：", state.products);
    },
    addProduct(state: State, product: Product) {
        state.products.push(product);
    },
    updateProduct(state: State, product: Product) {
        let index = _.findIndex(state.products, { id: product.id });
        if (index >= 0) {
            state.products.splice(index, 1, product);
        }
    },
    deleteProduct(state: State, product: Product) {
        let index = _.findIndex(state.products, { id: product.id });
        if (index >= 0) {
            state.products.splice(index, 1);
        }
    }
}

export default {
    state: initState,
    getters,
    actions,
    mutations
}